#include "const.h"

#ifdef _WIN32
char *i_realpath(const char *filename, char *resolvedname, size_t maxn) {
	static char buf[512];
	size_t i;
	DWORD r;

	if (!(r = GetFullPathNameA(filename, sizeof(buf), buf, (char **)0))) {
		errno = ENOSYS;
		return (char *)0;
	} else if(r >= (DWORD)maxn) {
		errno = ERANGE;
		return (char *)0;
	}

	for(i=0; i<sizeof(buf); i++) {
		if (!buf[i])
			break;

		if (buf[i]=='\\')
			buf[i] = '/';
	}

	if (buf[1]==':') {
		if (buf[0]>='A' && buf[0]<='Z')
			buf[0] = buf[0] - 'A' + 'a';
	}

	strncpy(resolvedname, buf, maxn-1);
	resolvedname[maxn-1] = 0;

	return resolvedname;
}
#else
char *i_realpath(const char *filename, char *resolvedname, size_t maxn) {
	static char buf[PATH_MAX + 1];

	if (maxn > PATH_MAX) {
		if (!realpath(filename, resolvedname))
			return (char *)0;

		resolvedname[PATH_MAX] = 0;
		return resolvedname;
	}

	if (!realpath(filename, buf))
		return (char *)0;

	buf[PATH_MAX] = 0;
	strncpy(resolvedname, buf, maxn);

	resolvedname[maxn-1] = 0;
	return resolvedname;
}
#endif
